//
//  JPVideoPlayerWBControlView.m
//  JPVideoPlayerDemo
//
//  Created by xin on 2018/4/13.
//  Copyright © 2018年 NewPan. All rights reserved.
//

#import "JPVideoPlayerWBControlView.h"
#import "UIView+WebVideoCache.h"
#import <Masonry.h>

@interface JPVideoPlayerWBControlView () <JPVideoPlayerProtocol>

@property (nonatomic, strong) UIButton *wb_playButton;
@property (nonatomic, weak) UIView *playerView;

@end

@implementation JPVideoPlayerWBControlView

- (instancetype)initWithControlBar:(UIView <JPVideoPlayerProtocol> *_Nullable)controlBar
                         blurImage:(UIImage *_Nullable)blurImage {
    self = [super initWithControlBar:controlBar
                           blurImage:blurImage];
    if(self){
        self.wb_playButton = ({
            UIButton *button = [UIButton new];
            [button setImage:[UIImage imageNamed:@"video_pause"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"video_play"] forState:UIControlStateSelected];
            [button addTarget:self action:@selector(wb_playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(self);
            }];
            button;
        });
        
        [self addSubview:controlBar];
    }
    return self;
}

- (void)wb_playButtonClick:(UIButton *)wb_playButton
{
    wb_playButton.selected = !wb_playButton.selected;
    BOOL isPlay = self.playerView.jp_playerStatus == JPVideoPlayerStatusBuffering ||
    self.playerView.jp_playerStatus == JPVideoPlayerStatusPlaying;
    isPlay ? [self.playerView jp_pause] : [self.playerView jp_resume];
}

#pragma mark - JPVideoPlayerProtocol

- (void)viewWillAddToSuperView:(UIView *)view {
    [super viewWillAddToSuperView:view];
    self.playerView = view;
    [self.controlBar viewWillAddToSuperView:view];
}

- (void)viewWillPrepareToReuse {
    [self.controlBar viewWillPrepareToReuse];
}

- (void)cacheRangeDidChange:(NSArray<NSValue *> *)cacheRanges {
    [self.controlBar cacheRangeDidChange:cacheRanges];
}

- (void)playProgressDidChangeElapsedSeconds:(NSTimeInterval)elapsedSeconds
                               totalSeconds:(NSTimeInterval)totalSeconds {
    [self.controlBar playProgressDidChangeElapsedSeconds:elapsedSeconds
                                            totalSeconds:totalSeconds];
}

- (void)didFetchVideoFileLength:(NSUInteger)videoLength {
    [self.controlBar didFetchVideoFileLength:videoLength];
}

@end
